<html lang="en-US">

<head>
    
<title>「连载八」对 RPC 方法做自定义认证 - 花落雨忧</title>

<meta property="og:title" content="「连载八」对 RPC 方法做自定义认证 - 花落雨忧">



    



    
    <meta property="description" content="在前面的章节中，我们介绍了两种（证书算一种）可全局认证的方法：
[&amp;hellip;] 而在实际需求中，常常会对某些模块的 RPC 方法做特殊认证或校验。今天将会讲解、实现这块的功能点
[&amp;hellip;] type PerRPCCredentials interface { GetRequestMetadata(ctx context.Context, uri ...string) &amp;hellip;">
    <meta property="og:description" content="在前面的章节中，我们介绍了两种（证书算一种）可全局认证的方法：
[&amp;hellip;] 而在实际需求中，常常会对某些模块的 RPC 方法做特殊认证或校验。今天将会讲解、实现这块的功能点
[&amp;hellip;] type PerRPCCredentials interface { GetRequestMetadata(ctx context.Context, uri ...string) &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/grpc/2018-10-14-per-rpc-credentials/">「连载八」对 RPC 方法做自定义认证</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/10/14</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="前言">前言</h2>
<p>在前面的章节中，我们介绍了两种（证书算一种）可全局认证的方法：</p>
<ol>
<li><a href="https://github.com/EDDYCJY/blog/blob/master/grpc/grpc-tls.md">TLS 证书认证</a></li>
<li><a href="https://github.com/EDDYCJY/blog/blob/master/grpc/ca-tls.md">基于 CA 的 TLS 证书认证</a></li>
<li><a href="https://github.com/EDDYCJY/blog/blob/master/grpc/interceptor.md">Unary and Stream interceptor</a></li>
</ol>
<p>而在实际需求中，常常会对某些模块的 RPC 方法做特殊认证或校验。今天将会讲解、实现这块的功能点</p>
<h2 id="课前知识">课前知识</h2>
<pre tabindex="0"><code>type PerRPCCredentials interface {
    GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
    RequireTransportSecurity() bool
}
</code></pre><p>在 gRPC 中默认定义了 PerRPCCredentials，它就是本章节的主角，是 gRPC 默认提供用于自定义认证的接口，它的作用是将所需的安全认证信息添加到每个 RPC 方法的上下文中。其包含 2 个方法：</p>
<ul>
<li>GetRequestMetadata：获取当前请求认证所需的元数据（metadata）</li>
<li>RequireTransportSecurity：是否需要基于 TLS 认证进行安全传输</li>
</ul>
<h2 id="目录结构">目录结构</h2>
<p>新建 simple_token_server/server.go 和 simple_token_client/client.go，目录结构如下：</p>
<pre tabindex="0"><code>go-grpc-example
├── client
│   ├── simple_client
│   ├── simple_http_client
│   ├── simple_token_client
│   └── stream_client
├── conf
├── pkg
├── proto
├── server
│   ├── simple_http_server
│   ├── simple_server
│   ├── simple_token_server
│   └── stream_server
└── vendor
</code></pre><h2 id="grpc">gRPC</h2>
<h3 id="client">Client</h3>
<pre tabindex="0"><code>package main

import (
	&#34;context&#34;
	&#34;log&#34;

	&#34;google.golang.org/grpc&#34;

	&#34;github.com/EDDYCJY/go-grpc-example/pkg/gtls&#34;
	pb &#34;github.com/EDDYCJY/go-grpc-example/proto&#34;
)

const PORT = &#34;9004&#34;

type Auth struct {
	AppKey    string
	AppSecret string
}

func (a *Auth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{&#34;app_key&#34;: a.AppKey, &#34;app_secret&#34;: a.AppSecret}, nil
}

func (a *Auth) RequireTransportSecurity() bool {
	return true
}

func main() {
	tlsClient := gtls.Client{
		ServerName: &#34;go-grpc-example&#34;,
		CertFile:   &#34;../../conf/server/server.pem&#34;,
	}
	c, err := tlsClient.GetTLSCredentials()
	if err != nil {
		log.Fatalf(&#34;tlsClient.GetTLSCredentials err: %v&#34;, err)
	}

	auth := Auth{
		AppKey:    &#34;eddycjy&#34;,
		AppSecret: &#34;20181005&#34;,
	}
	conn, err := grpc.Dial(&#34;:&#34;+PORT, grpc.WithTransportCredentials(c), grpc.WithPerRPCCredentials(&amp;auth))
	...
}
</code></pre><p>在 Client 端，重点实现 <code>type PerRPCCredentials interface</code> 所需的方法，关注两点即可：</p>
<ul>
<li>struct Auth：GetRequestMetadata、RequireTransportSecurity</li>
<li>grpc.WithPerRPCCredentials</li>
</ul>
<h3 id="server">Server</h3>
<pre tabindex="0"><code>package main

import (
	&#34;context&#34;
	&#34;log&#34;
	&#34;net&#34;

	&#34;google.golang.org/grpc&#34;
	&#34;google.golang.org/grpc/codes&#34;
	&#34;google.golang.org/grpc/metadata&#34;
	&#34;google.golang.org/grpc/status&#34;

	&#34;github.com/EDDYCJY/go-grpc-example/pkg/gtls&#34;
	pb &#34;github.com/EDDYCJY/go-grpc-example/proto&#34;
)

type SearchService struct {
	auth *Auth
}

func (s *SearchService) Search(ctx context.Context, r *pb.SearchRequest) (*pb.SearchResponse, error) {
	if err := s.auth.Check(ctx); err != nil {
		return nil, err
	}
	return &amp;pb.SearchResponse{Response: r.GetRequest() + &#34; Token Server&#34;}, nil
}

const PORT = &#34;9004&#34;

func main() {
	...
}

type Auth struct {
	appKey    string
	appSecret string
}

func (a *Auth) Check(ctx context.Context) error {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return status.Errorf(codes.Unauthenticated, &#34;自定义认证 Token 失败&#34;)
	}

	var (
		appKey    string
		appSecret string
	)
	if value, ok := md[&#34;app_key&#34;]; ok {
		appKey = value[0]
	}
	if value, ok := md[&#34;app_secret&#34;]; ok {
		appSecret = value[0]
	}

	if appKey != a.GetAppKey() || appSecret != a.GetAppSecret() {
		return status.Errorf(codes.Unauthenticated, &#34;自定义认证 Token 无效&#34;)
	}

	return nil
}

func (a *Auth) GetAppKey() string {
	return &#34;eddycjy&#34;
}

func (a *Auth) GetAppSecret() string {
	return &#34;20181005&#34;
}
</code></pre><p>在 Server 端就更简单了，实际就是调用 <code>metadata.FromIncomingContext</code> 从上下文中获取 metadata，再在不同的 RPC 方法中进行认证检查</p>
<h3 id="验证">验证</h3>
<p>重新启动 server.go 和 client.go，得到以下结果：</p>
<pre tabindex="0"><code>$ go run client.go
2018/10/05 20:59:58 resp: gRPC Token Server
</code></pre><p>修改 client.go 的值，制造两者不一致，得到无效结果：</p>
<pre tabindex="0"><code>$ go run client.go
2018/10/05 21:00:05 client.Search err: rpc error: code = Unauthenticated desc = invalid token
exit status 1
</code></pre><h3 id="一个个加太麻烦">一个个加太麻烦</h3>
<p>我相信你肯定会问一个个加，也太麻烦了吧？有这个想法的你，应当把 <code>type PerRPCCredentials interface</code> 做成一个拦截器（interceptor）</p>
<h2 id="总结">总结</h2>
<p>本章节比较简单，主要是针对 RPC 方法的自定义认证进行了介绍，如果是想做全局的，建议是举一反三从拦截器下手哦。</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-grpc-example">go-grpc-example</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-12-grpc-http/">「连载七」让你的服务同时提供 HTTP 接口</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-10-interceptor/">「连载六」Unary and Stream interceptor</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-08-ca-tls/">「连载五」基于 CA 的 TLS 证书认证</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-07-grpc-tls/">「连载四」TLS 证书认证</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-09-24-stream-client-server/">「连载三」gRPC Streaming, Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/grpc" title="View all posts tagged match">grpc</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/grpc/2018-10-12-grpc-http/"
                                                    rel="prev">「连载七」让你的服务同时提供 HTTP 接口</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/grpc/2018-10-16-deadlines/">「连载九」gRPC Deadlines</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>